package cn.tutu.blockchain.exception;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

import org.apache.shiro.authc.AuthenticationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.tutu.blockchain.common.MsgObj;

/**
 * 
 * <p>
 * Title: GlobalExceptionHandler
 * </p>
 * <p>
 * Description: 全局异常
 * </p>
 * 
 * @author 眭善峰
 * @date 2018年4月25日
 *
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

	private static Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

	@ExceptionHandler(value = Exception.class)
	public MsgObj exceptionHandler(HttpServletRequest request, Exception exception) throws Exception {
		LOGGER.error(exception.getMessage(), exception);
		MsgObj msg = null;

		if (exception instanceof BindException) {
			// 返回参数校验错误具体信息
			BindException e = (BindException) exception;
			List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
			StringBuilder sb = new StringBuilder();
			for (ObjectError error : allErrors) {
				sb.append(error.getDefaultMessage());
			}
			msg = MsgObj.buildExceptionMsg(sb.toString());
		} else if (exception instanceof AuthenticationException) {
			msg = MsgObj.buildExceptionMsg("登录失败，用户名不存在或密码错误!");
		} else if (exception instanceof BusinessException) {
			msg = MsgObj.buildExceptionMsg(exception.getMessage());
		} else {
			msg = MsgObj.buildExceptionMsg("系统异常!");
		}

		return msg;
	}

	/**
	 * 校验单个参数异常
	 * 
	 * @param ex
	 * @return
	 */
	@ExceptionHandler(value = ConstraintViolationException.class)
	public MsgObj ConstraintViolationExceptionHandler(ConstraintViolationException ex) {
		String msg = null;
		Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations();
		Iterator<ConstraintViolation<?>> iterator = constraintViolations.iterator();
		while (iterator.hasNext()) {
			ConstraintViolation<?> cvl = iterator.next();
			msg = cvl.getMessageTemplate();
		}

		return MsgObj.buildExceptionMsg(msg);
	}

}
